﻿#define _CRT_SECURE_NO_WARNINGS 1

/*
堆的向上/下调整，建堆的时间复杂度及其数学推导过程
void AdjustDown(int* a, int size, int parent){}
void AdjustUp(int* a, int child)
建堆的时间复杂度：O(N)
推导过程：参考博客 https://blog.csdn.net/qq_52433890/article/details/121502538
*/

//向上调整
void AdjustUp(int* a, int child)
{
	int parent = (child - 1) / 2;
	//while(parent >= 0)
	//有巧合
	while (child > 0)
	{
		//交换孩子和父亲
		if (a[child] < a[parent])
		{
			int tmp = a[parent];
			a[parent] = a[child];
			a[child] = a[parent];

			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

//向下调整
void AdjustDown(int* a, size_t size, int parent)
{
	int child = parent * 2 + 1;
	while (child < size)
	{
		//假设左孩子小是错误的，就加加变成右孩子
		if (child + 1 < size && a[child + 1] < a[child])
		{
			++child;
		}

		if (a[child] < a[parent])
		{
			int tmp = a[parent];
			a[parent] = a[child];
			a[child] = a[parent];

			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

